from ..base_downloader import *
from ..base_downloader_firefox import BaseDownloaderFirefox


class Task48(BaseDownloaderFirefox):
    def login(self):
        username_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "UserName"))
        )
        password_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "PassWord"))
        )
        username_field.send_keys(self.username)
        password_field.send_keys(self.password)

        captcha_input = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "vcode"))
        )
        captcha_solution = solve_captcha_image(self.driver, (By.ID, "vcodeimg"))
        if captcha_solution:
            captcha_input.clear()
            captcha_input.send_keys(captcha_solution)


        self.driver.find_element(By.ID, "login").click()

        self.random_sleep(0.5)
        self.accept_alert_dialog()
        self.random_sleep(1.5)

    def retrieve_data(self):
        self.click_query_button()       
        self.set_start_and_end_dates()
        self.click_retrieve_button()

    def click_query_button(self):
        try:
            WebDriverWait(self.driver, 10).until(
                EC.frame_to_be_available_and_switch_to_it((By.ID, "mainFrame"))
            )

            query_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, "//a[text()='网上查询']"))
            )
            query_button.click()

            query_research_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, "//a[text()='流量流向查询']"))
            )
            query_research_button.click()

        except Exception as e:
            logger.exception(f"An error occurred while clicking the query button: {e}")

    def set_start_and_end_dates(self):

        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, "main"))
        )

        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, "conditionframe"))
        )
        
        start_date_input = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "BeginTime"))
            )
        start_date_input.clear()  
        start_date_input.send_keys(self.start_date)

        end_date_input = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.ID, "EndTime"))
            )
        end_date_input.clear()
        end_date_input.send_keys(self.end_date)

        self.capture_screenshot()

    def click_retrieve_button(self):
        try:
            retrieve_button = self.driver.find_element(By.ID, 'btnQuery').click()
            retrieve_button.click()
        except Exception as e:
            logger.exception(f"An error occurred while clicking the retrieve button: {e}")

    def export_excel(self):
        self.capture_screenshot()

        self.driver.switch_to.default_content()
        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, "mainFrame"))
        )
        self.random_sleep(2)
        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, "main"))
        )
        self.random_sleep(2)

        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, "reportframe"))
        )
        self.random_sleep(2)

        export_button = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.ID, 'ReportViewerControl_ctl05_ctl04_ctl00_ButtonLink'))
        )
        export_button.click()
        self.random_sleep(2)

        excel_export_link = WebDriverWait(self.driver, 30).until(
            EC.element_to_be_clickable((By.XPATH, '//a[@title="Excel"]'))
        )
        excel_export_link.click()
        self.random_sleep(8)

        downloaded_file = self.get_latest_downloaded_file()

        new_file_name = f"{self.site_name}_exported_click_button.xlsx"
        destination_path = os.path.join(self.task_download_dir, new_file_name)

        process_downloaded_file(downloaded_file, destination_path)
        logger.info(f"Processed and saved file to: {destination_path}")

        self.random_sleep(8)
        self.delete_downloaded_files()

    def page_html_to_excel(self):
        self.driver.switch_to.default_content()
        data_frame = pd.read_html(self.driver.page_source)[0]
        target_path = os.path.join(
            self.task_download_dir, f"{self.site_name}_page_html_to_excel.xlsx"
        )
        data_frame.to_excel(target_path, index=False)


    def download_file(self):
        #self.page_html_to_excel()  # One way to download the Excel file
        self.export_excel()        # Another way to download the Excel file; use either method

    def delete_downloaded_files(self):
        """Delete the original downloaded file after processing."""
        try:
            downloaded_file = self.get_latest_downloaded_file()
            if os.path.exists(downloaded_file):
                os.remove(downloaded_file)
                logger.info(f"Deleted original downloaded file: {downloaded_file}")
        except Exception as e:
            logger.error(f"Error deleting downloaded file: {e}")